<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class App extends MY_Controller {
	
	function __construct()
	{
		parent::__construct(); 
		
		$this->load->model('it_userid_model', 'User');
		$this->load->model('it_menu_model', 'Menu');
		$this->load->model('sis_store_procedure_model', 'SP');
	}
	
	function index(){
		$this -> login();
	}
	
	function quicklink(){
		$data["returnpath"] = get('path');
		viewByTemplate('app/quicklink', $data, 'frontend');
	}
	
	function quicklogin(){
		$ls_response = "";
		$ls_userid = strtoupper(decrypt(get('u'),$this->config->item('encryption_key')));
		$ls_password = strtoupper(decrypt(decrypt(get('p'),$this->config->item('encryption_key')),$this->config->item('encryption_key')));
		$ls_invisible = '0';

		$ls_ip = client_ip();
		$ls_now = NOW;
		$ls_sessid = md5($ls_userid . $ls_now . $ls_ip);
		$ls_info_os = client_browser();
		$ls_info_browser = client_OS();

		
		$LOCK_LOGIN_BY_IP = ($this->web_option("LOCK_LOGIN_BY_IP") == "1");
		$SUCCESS_LOGIN = $this->App->CheckLogin($ls_userid, $ls_password);
		$ls_session_expired = $this->web_option("SESSION_EXPIRED");
		$SESSION_EXPIRED = ($ls_session_expired == "" ? 30 : intval($ls_session_expired));
		$dr_session = $this->App->GetUserSessionByOwner($ls_userid);


		if (!$SUCCESS_LOGIN)
		{
			$ls_response .= "Login gagal, user atau password salah";
			echo $ls_response;
		}
		else if ($SUCCESS_LOGIN)
		{
			// Set Session
			$arr_session['gs_ip']		= $ls_ip;
			$arr_session['gs_userid']	= $ls_userid;
			$arr_session['gs_sessid']	= $ls_sessid;

			$dr_user = $this->User->GetSingle($ls_userid);
			$arr_session['gs_username']	= $dr_user['user_name'];
			$arr_session['gs_culture']	= $dr_user['culture_id'];
			$arr_session['gs_office_code'] = $dr_user['office_code'];

			$new_session['sessid']		= $ls_sessid;
			$new_session['owner']		= $ls_userid;
			$new_session['ipaddress']	= $ls_ip;
			$new_session['invisible']	= $ls_invisible;
			$new_session['info']		= getenv("HTTP_USER_AGENT");
			$new_session['browser']		= $ls_info_browser;
			$new_session['os']			= $ls_info_os;
			$new_session['role']		= $this->App->GetUserDefaultRole($ls_userid);
			$new_session['start']		= NOW;
			$new_session['expired']		= strtotime(@date("Y-m-d H:i:s", strtotime("+".$SESSION_EXPIRED." minutes")));
			
			$this->session->set_userdata('arr_session', $new_session);
			$this->App->CreateSession($new_session);

			redirect(base_url().'app/system/?path='.get('path'));
		}
		
		
	}
	
	function login(){
		$data['site_name']	= $this->web_option('site_name');
		viewByTemplate('app/login', $data, 'frontend');
	}
	
	function checklogin(){
		// Get String into Variable
		$ls_response = "";
		$ls_userid = strtoupper(trim(post("user_id")));
		$ls_password = strtoupper(trim(post("password")));
		$ls_invisible = post("invisible");

		$ls_ip = client_ip();
		$ls_now = NOW;
		$ls_sessid = md5($ls_userid . $ls_now . $ls_ip);
		$ls_info_os = client_browser();
		$ls_info_browser = client_OS();


		$LOCK_LOGIN_BY_IP = ($this->web_option("LOCK_LOGIN_BY_IP") == "1");
		$SUCCESS_LOGIN = $this->App->CheckLogin($ls_userid, $ls_password);
		$ls_session_expired = $this->web_option("SESSION_EXPIRED");
		$SESSION_EXPIRED = ($ls_session_expired == "" ? 30 : intval($ls_session_expired));
		$dr_session = $this->App->GetUserSessionByOwner($ls_userid);


		if ($ls_userid == "" || $ls_password == "")
		{
			$ls_response .= "Silahkan isi user dan password";
		}
		else if (@ereg("[^a-zA-Z0-9_.]", $ls_userid) || @ereg("[^a-zA-Z0-9_.]", $ls_password))
		{
			$ls_response .= "Isi user dan password dengan alphanumeric [a-zA-Z0-9_.]";
		}
		else if ($LOCK_LOGIN_BY_IP && ($dr_session!=NULL && $dr_session['ipaddress']!="" && $dr_session['ipaddress'] != $ls_ip))
		{
			$ls_response .= "User " . $ls_userid . " sudah login dari ip " . $ls_ip;
		}
		else if (!$SUCCESS_LOGIN)
		{
			$ls_response .= "Login gagal, user atau password salah";
		}
		else if ($SUCCESS_LOGIN)
		{
			// Set Session
			$arr_session['gs_ip']		= $ls_ip;
			$arr_session['gs_userid']	= $ls_userid;
			$arr_session['gs_sessid']	= $ls_sessid;

			$dr_user = $this->User->GetSingle($ls_userid);
			$arr_session['gs_username']	= $dr_user['user_name'];
			//$arr_session['gs_culture']	= $dr_user['culture_id'];
			//$arr_session['gs_office_code'] = $dr_user['office_code'];

			$new_session['sessid']		= $ls_sessid;
			$new_session['owner']		= $ls_userid;
			$new_session['ipaddress']	= $ls_ip;
			$new_session['st_invisible']= $ls_invisible;
			$new_session['info']		= getenv("HTTP_USER_AGENT");
			$new_session['browser']		= $ls_info_browser;
			$new_session['os']			= $ls_info_os;
			$new_session['app_id']		= $this->App->GetUserDefaultApp($ls_userid);
			$new_session['role_id']		= $this->App->GetUserDefaultRole($ls_userid);
			$new_session['session_start']	= NOW;
			$new_session['session_expire']	= @date("Y-m-d H:i:s", strtotime("+".$SESSION_EXPIRED." minutes"));
			
			$this->session->set_userdata('arr_session', $new_session);
			$this->App->CreateSession($new_session);

			$ls_response = "OK";
		}
		
		echo $ls_response;
	}
	
	function logout(){
		$this->session_refresh();
		$this->db->delete('it_session',array('sessid'=>_SESSID));
		$this->session->sess_destroy();
		redirect(base_url());
	}
	
	function sessionexpirecontent()
	{
		echo "Session Expired";
	}

	function sessionexpireiframe()
	{
		$ls_returnpath = ""; //try { ls_returnpath = MySession.Current.gs_returnpath; } catch { }
		echo "<script type=\"text/javascript\">alert('Session Expired'); parent.location.href = '" . base_url() . "app/login/?returnpath=" . base64_encode($ls_returnpath) . "'; try { window.event.returnValue = false } catch (e) { }</script>";
	}

	function sessionexpireredirect()
	{
		$ls_returnpath = "";
		echo "<script type=\"text/javascript\">location.href = '" . base_url() . "app/login/?returnpath=" . base64_encode($ls_returnpath) . "'; try { window.event.returnValue = false } catch (e) { }</script>";
	}
	
	function select_app()
	{	
		$this->secure_session();
		$arr_session	= $this->session_read();
		
		$data['arr_session']	= $arr_session;
		
		$ls_ip		= client_ip();
		$ls_userid	= $arr_session['user_id'];
		$ls_sessid	= $arr_session['sessid'];
		$data["sessid"]		= $ls_sessid;
		$data["time_adjust"] = $this->config->item('time_adjust');
		$data["returnpath"] = base64_encode(get('path'));
		
		// Check Is Developer
		$lb_dev = $this->App->UserIsDeveloper($ls_userid);
		$data["dev"] = ($lb_dev ? 1 : 0);

		// Get User
		$dr_user = $this->User->GetSingle($ls_userid);
		$data["culture"] = 'id';//$dr_user["culture_id"];
		
		// Get All Application
		$data["arr_app"] = $this->App->GetApplication();
		if(count($data["arr_app"]) == 1){
			
			$this->db->update('it_session', array('app_id' => $data["arr_app"][0]['app_id']), array('sessid' => _SESSID));
			$this->system();
			
		}else{
		
			$data['title'] = $this->web_option('SITE_NAME');
			viewByTemplate('app/select_app', $data, 'backend');
			
		}
	}
	
	function system()
	{
		$this->secure_session();
		$arr_session	= $this->session_read();
		
		$data['arr_session']	= $arr_session;
		
		$ls_ip		= client_ip();
		$ls_userid	= $arr_session['user_id'];
		$ls_sessid	= $arr_session['sessid'];
		$data["sessid"]		= $ls_sessid;
		$data["time_adjust"] = $this->config->item('time_adjust');
		$data["returnpath"] = base64_encode(get('path'));
		
		// Check Is Developer
		$lb_dev = $this->App->UserIsDeveloper($ls_userid);
		$data["dev"] = ($lb_dev ? 1 : 0);

		// Get User
		$dr_user = $this->User->GetSingle($ls_userid);
		$data["culture"] = 'id';//$dr_user["culture_id"];
		
		// Get User Role
		$data["arr_role"] = $this->App->GetUserGetRole($ls_userid);
		if(count($data["arr_role"]) == 1 || (ROLE == '' && count($data["arr_role"]) > 0)){
			if(trim($this->get_data("SELECT ROLE_ID FROM IT_SESSION WHERE SESSID = '"._SESSID."'")) == ''){
				$this->db->update('it_session', array('role_id' => $data["arr_role"][0]['role_id']), array('sessid' => _SESSID));
			}
		}
		
		// Get First Menu
		$data["arr_firstmenu"] = $this->Menu->GetFirstLevelMenuByRole();
		
		// Get All Application
		$data["arr_app"] = $this->App->GetApplication();
		
		$data['title'] = $this->web_option('SITE_NAME');
		
		viewByTemplate('app/system', $data, 'system_backend');
	}
	
	function submenu_data(){
		$this->secure_session();
		$arr_menu = $this->Menu->GetChildMenuByRole(get('menu_id'));
		echo ($arr_menu== NULL ? '[]' : json_encode($arr_menu));
	}
	
	function dashboard()
	{
		$this->secure_session();
		$arr_session	= $this->session_read();
		
		$ls_userid = $arr_session['user_id'];

		// Get User Role
		$data["arr_role"] = $this->App->GetUserGetRole($ls_userid);
		
		$data["arr_directorate"] = array();
		
		$li_year = get('an_year')=='' ? date('Y')+1 : get('an_year');
		$ls_status = get('as_approval_status')=='' ? 'FINAL' : get('as_approval_status');
		
		$tot_budget= array();
		$tot_realization= array();
		
		$arr_graph = array(array('name'=>'Budget', 'data'=>$tot_budget), array('name'=>'Realization', 'data'=>$tot_realization));
		$data["arr_graph"] = json_encode($arr_graph);
		$data["ln_year"] = $li_year;
		$data["ls_status"] = $ls_status;
		
		
		$this->load->view('app/dashboard', $data);
		
	}
	
	function ajax_change_app(){
		$this->secure_session();
		$arr_session	= $this->session_read();
		
		$app_id	= post('app_id');
		$this->db->update('it_session', array('app_id' => $app_id, 'role_id' => ''), array('sessid' => _SESSID));
	}
	
	function ajax_change_role(){
		$this->secure_session();
		$arr_session	= $this->session_read();
		
		$role_id	= post('role_id');
		if(intval($this->get_data("	SELECT	COUNT(1)
									FROM	it_session a
											JOIN it_user_role b ON a.owner = b.user_id
									WHERE	a.sessid = '"._SESSID."' AND b.role_id = '".$role_id."'")) > 0){
			$this->db->update('it_session', array('role_id' => $role_id), array('sessid' => _SESSID));
		}
	}
	
	function api($view='', $i=0)
	{
		$this->secure_session();
		$arr_session	= $this->session_read();
		
		$ls_userid = $arr_session['user_id'];
		
		// Check Is Developer
		$lb_dev = $this->App->UserIsDeveloper($ls_userid);
		$data["dev"] = ($lb_dev ? 1 : 0);
		$data["i"] = intval($i);

		if ($lb_dev) { $this->load->view("app/api" . ($view== "" ? "" : "_" . $view)); }
		else { echo "<br /><br /><img src=\"" . base_url() . "content/images/ico_error.png\" border=\"0\" style=\"margin-right:10px\" />Access Restricted, You're Not Developer..!!"; }
	}
	
	function random_image(){
		$this->load->view('app/random_image');
	}
	
	function download(){
		$this -> secure_session();
		/* copyleft : http://elouai.com/force-download.php */
		
		$filename 			= APPPATH . '/file/cache/' . get('file');
		$download_file_name	= get('filename');
		$download_file_name	= str_replace(':','.', str_replace(' ','_', str_replace('_NOW_', NOW, $download_file_name)));
		
		// required for IE, otherwise Content-disposition is ignored
		if(ini_get('zlib.output_compression'))
			ini_set('zlib.output_compression', 'Off');
		
		// addition by Jorg Weske
		$file_extension = strtolower(substr(strrchr($filename,"."),1));
		
		if($filename == "") 
		{
			echo "<script type=\"text/javascript\">alert('ERROR: download file NOT SPECIFIED.');</script>";
			exit;
		} elseif ( ! file_exists( $filename ) ) 
		{
			echo "<script type=\"text/javascript\">alert('ERROR: File $filename not found.');</script>";
			exit;
		};
		
		switch( $file_extension )
		{
			case "pdf": $ctype="application/pdf"; break;
			case "exe": $ctype="application/octet-stream"; break;
			case "zip": $ctype="application/zip"; break;
			case "doc": $ctype="application/msword"; break;
			case "xls": $ctype="application/vnd.ms-excel"; break;
			case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
			case "gif": $ctype="image/gif"; break;
			case "png": $ctype="image/png"; break;
			case "jpeg":
			case "jpg": $ctype="image/jpg"; break;
			default: $ctype="application/force-download";
		}
		header("Pragma: public"); // required
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private",false); // required for certain browsers 
		header("Content-Type: $ctype");
		// change, added quotes to allow spaces in filenames, by Rajkumar Singh
		//header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
		header("Content-Disposition: attachment; filename=\"".$download_file_name."\";" );
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".filesize($filename));
		readfile("$filename");
		exit();
	}
	
	function test_sp(){
		$this->SP->SP_SIS_GEN_TAGIHAN(array('p_bln_transaksi' => '30/11/2013'));
	}
	
	function phpinfo(){
		phpinfo();
	}
}
?>